package com.bobo.netty.server.websocketchat;

import com.bobo.netty.common.Constants;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 聊天服务引导类
 */
@Service
public class WebSocketChatServer {
    private ServerBootstrap serverBootstrap;
    private EventLoopGroup boss;
    private EventLoopGroup worker;
    @Resource
    private WebSocketChatServerInitializer webSocketChatServerInitializer;
    @Async("webSocketStartThreadSingle")
    public void open() throws InterruptedException {
        serverBootstrap = new ServerBootstrap();
        boss = new NioEventLoopGroup();
        worker = new NioEventLoopGroup();
        serverBootstrap.group(boss, worker)
                .channel(NioServerSocketChannel.class)
                .childHandler(webSocketChatServerInitializer)
                .option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.SO_KEEPALIVE,true);
        ChannelFuture sync = serverBootstrap.bind(Constants.CHAT_PORT).sync();
        sync.channel().closeFuture().sync();
    }
    public void close() throws InterruptedException {
        boss.shutdownGracefully();
        worker.shutdownGracefully();
    }

    public static void main(String[] args) throws InterruptedException {
        new WebSocketChatServer().open();
    }
}
